package ernie.server.context;

import java.io.IOException;

import misc.HTMLStringStream;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import ernie.pages.Error404Page;
import ernie.server.NoSuchPageException;
import ernie.server.PageDispatcher;

/**
 * @author Filip Lindqvist <buggfille@gmail.com>
 * @created 11:22:42 AM - Nov 16, 2011
 */
public class PageFilteringContext implements HttpHandler {
    private final PageDispatcher pd;

    public PageFilteringContext(PageDispatcher pd) {
        this.pd = pd;
    }

    @Override
    public void handle(HttpExchange t) {
        try {
            String page = t.getRequestURI().toString();
            page = page.substring(page.lastIndexOf('/') + 1);
            if (pd.isPage(page)) {
                String content = "";
                try {
                    content = pd.getPage(page);
                } catch (NoSuchPageException ex) {
                    ex.printStackTrace();
                }
                HTMLStringStream hss = new HTMLStringStream(t);
                hss.write(content);
                hss.close();
            } else {
                HTMLStringStream hss = new HTMLStringStream(t, 404);
                hss.write(new Error404Page().getContent());
                hss.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}
